class BillingOrder < ActiveRecord::Base
  has_many :billing_transactions
  has_one :billing_account
  
  # Validations -----------------------------------------------------
  validates_presence_of   :account_id, :amount, :on => :create
  
  # validates_uniqueness_of :user_id
  # validates_associated :line_items, :message => "are not valid"
  validates_numericality_of :amount, :account_id
  # -----------------------------------------------------------------
  
  after_create :purchase
  
  #----- Act as FINITE STATE MACHINE -------------
    acts_as_state_machine :initial => :pending, :column => :status

    # !!!!   for other special functions that
    # requires to change the status
    # use callback
    # state :inactive, :column => :status, :enter => :method1, .... read documentations

    state :pending, :column => :status
    state :authorized, :column => :status
    state :paid, :column => :status
    state :payment_declined, :column => :status
    

    event :payment_authorized do
      transitions :from => :pending, 
                  :to   => :authorized

      transitions :from => :payment_declined, 
                  :to   => :authorized
    end

    event :payment_captured do
      transitions :from => :pending, 
                  :to   => :paid

      transitions :from => :authorized, 
                  :to   => :paid
    end

    event :payment_declined do
      transitions :from => :pending, 
                  :to   => :payment_declined

      transitions :from => :payment_declined, 
                  :to   => :payment_declined

      transitions :from => :authorized, 
                  :to   => :authorized
    end
  #-----------------------------------------------
  def purchase
    acc = BillingAccount.new
    begin
      acc = BillingAccount.find(account_id)
    rescue ActiveRecord::RecordNotFound => e
      self.errors.add_to_base e.inspect + "There is no accounts #{account_id}"
      raise ZepFrog::CustomError, self.class.to_s + "__" + "purchase" + "__" + e.inspect
    end
    
    # if acc.nil raise ZepFrog::CustomError, "There is no account #{account_id} #{(acc.to_s || 'hhh')}"
      
       #      
       # create_table :billing_orders do |t|
       #   t.integer :user_id
       #   t.string :status
       #   t.string :action
       #   t.string :ref_operation_id
       #   t.text :note
       #   t.string :ip_address
       #   t.integer :account_id
       #   t.float :amount
       #   t.float :amount_tax
       #   t.float :amount_shipping
       #   t.float :amount_total
       #   t.date :created_at
       #   t.date :updated_at
    
    transaction do
      # self.new
      purchase = BillingTransaction.profile_transaction({
                          :customer_profile_id => acc.customer_profile_id,
                          :customer_payment_profile_id => acc.customer_payment_id, 
                          :order_id => self.id, 
                          :type => :auth_only, # auth_capture
                          :amount => amount})
      
      billing_transactions.push(purchase)
      
      if purchase.auth_id
        payment_captured!
      else
        payment_declined!
      end
      
      purchase
    end
  # end
  end
  
  # # BEGIN authorize_payment
  # def authorize_payment(credit_card, options = {})
  #   acc = BillingAccount.find(account_id)
  # 
  #   options[:order_id] = number
  # 
  #   transaction do
  # 
  #     # authorization = BillingTransaction.profile_transaction(amount, credit_card, options)
  #     authorization = BillingTransaction.profile_transaction({
  #                         :customer_profile_id => acc.customer_profile_id,
  #                         :customer_payment_profile_id => acc.customer_payment_id, 
  #                         :order_id => order.id, 
  #                         :type => :auth_only, 
  #                         :amount => amount})
  #     transactions.push(authorization)
  # 
  #     if authorization.success?
  #       payment_authorized!
  #     else
  #       transaction_declined!
  #     end
  # 
  #     authorization
  #   end
  # end
  # # END authorize_payment
  # 
  
  # def self.authorize(options = {})
  #    # billing_address = {:zip => options[:zipcode]}
  #    # options = {:address => {}, :billing_address => billing_address}
  #    
  #    # testing purpose   re-write
  #    
  #    addr = {:address => {}, :billing_address => {:zip => options[:zipcode]}}
  #    authorize_response = TRANSACTION_GATEWAY.authorize(options[:amount], options[:credit_card], addr)
  #    # Authorize for subscription price dollars ($600 == 60000 cents) 
  #    # auth_response = gateway.purchase(FPRICE, credit_card, options)
  #    if authorize_response.success?
  #      return true, authorize_respons e.authorization
  #    else
  #      return false, authorize_response
  #    end
  #    
  #  end
  #  
  #  def self.capture(options = {})
  #    # billing_address = {:zip => options[:zipcode]}
  #    # options = {:address => {}, :billing_address => billing_address}
  #    
  #    # testing purpose   re-write
  #    
  #    addr = {:address => {}, :billing_address => {:zip => options[:zipcode]}}
  #    capture_response = TRANSACTION_GATEWAY.capture(options[:amount], options[:credit_card], addr)
  #    # Authorize for subscription price dollars ($600 == 60000 cents) 
  #    # auth_response = gateway.purchase(FPRICE, credit_card, options)
  #    if capture_response.success?
  #      return true, capture_response.authorization
  #    else
  #      return false, capture_response
  #    end
  #    
  #  end
  #  
  #  def self.purchase(options = {})
  #    # billing_address = {:zip => options[:zipcode]}
  #    # options = {:address => {}, :billing_address => billing_address}
  #    
  #    # testing purpose   re-write
  #    
  #    addr = {:address => {}, :billing_address => {:zip => options[:zipcode]}}
  #    purchase_response = TRANSACTION_GATEWAY.purchase(options[:amount], options[:credit_card], addr)
  #    # Authorize for subscription price dollars ($600 == 60000 cents) 
  #    # auth_response = gateway.purchase(FPRICE, credit_card, options)
  #    if purchase_response.success?
  #      return true, purchase_response.authorization
  #    else
  #      return false, purchase_response
  #    end
  #    
  #  end
  

end
